package com.agrm.address.service.impl;

import com.agrm.address.mapper.AddressMapper;
import com.agrm.address.service.AddressService;
import com.agrm.address.service.ChinaRegionsService;
import com.agrm.model.address.dto.AddressQuery;
import com.agrm.model.address.pojo.Address;
import com.agrm.model.address.pojo.ChinaRegions;
import com.agrm.model.common.dtos.PageRequestDto;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private ChinaRegionsService chinaRegionsService;

    /**
     * 查询列表
     *
     * @param page  分页参数
     * @param query 查询条件
     * @return 分页地址列表
     */


    @Override
    public Page<Address> queryList(PageRequestDto page, AddressQuery query) {
        page.checkParam();
        // 创建MyBatis-Plus分页对象
        Page<Address> pages = new Page<>(page.getPage(), page.getSize());
        // 构建查询条件
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();

        if (query != null) {
            if (query.getReginDetail() != null && !query.getReginDetail().isEmpty()) {
                wrapper.like(Address::getReceiver, query.getReginDetail());
            }
        }
        // 执行分页查询
        Page<Address> resultPage = addressMapper.selectPage(pages, wrapper);

        // 获取所有regionId
        Set<Integer> regionIds = resultPage.getRecords().stream()
                .map(Address::getRegionId)
                .collect(Collectors.toSet());

        if (!regionIds.isEmpty()) {
            // 批量查询ChinaRegions
            List<ChinaRegions> regions = chinaRegionsService.findAll(); // 获取所有地区数据
            Map<Integer, ChinaRegions> regionMap = regions.stream()
                    .filter(region -> regionIds.contains(region.getId()))
                    .collect(Collectors.toMap(ChinaRegions::getId, region -> region));

            // 设置region到Address对象中
            resultPage.getRecords().forEach(address -> {
                ChinaRegions region = regionMap.get(address.getRegionId());
                address.setRegion(region);
            });
        }

        return resultPage;
    }

    /**
     * 根据会员ID查询地址列表
     * @param memberId
     * @return
     */
    @Override
    public List<Address> getByMemberId(Integer memberId) {
        LambdaQueryWrapper<Address> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.eq(Address::getMemberId, memberId);
        return addressMapper.selectList(lambdaQuery);
    }
}